package com.rongzhe.house.pay;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.rongzhe.house.common.utils.DateUtil;
import com.rongzhe.house.common.utils.SignUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * Created by hggxg on 2017/11/15.
 */
@Deprecated
@Service
public class PayServiceImpl implements PayService {

    private static final Logger LOGGER = LoggerFactory.getLogger(PayServiceImpl.class);


    @Autowired
    private AliPayConfig alipayConfig;


    @Override
    public String getSign(Map<String, String> map, String rsaKey, boolean rsa2) {

        List<String> keys = new ArrayList(map.keySet());

        Collections.sort(keys);

        StringBuilder authInfo = new StringBuilder();
        for (int i = 0; i < keys.size() - 1; i++) {
            String key = keys.get(i);
            String value = map.get(key);
            authInfo.append(buildKeyValue(key, value, false));
            authInfo.append("&");
        }
        String tailKey = keys.get(keys.size() - 1);
        String tailValue = map.get(tailKey);
        authInfo.append(buildKeyValue(tailKey, tailValue, false));

        String oriSign = SignUtils.sign(authInfo.toString(), rsaKey, rsa2);
        String encodedSign = "";
        try {
            encodedSign = URLEncoder.encode(oriSign, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return "sign=" + encodedSign;

    }

    @Override
    public AliPayPost checkSign(Map<String, String> paramMap) {

        paramMap.remove("sign_type");
        String sing = (String) paramMap.get("sign");

        String content = AlipaySignature.getSignCheckContentV2(paramMap);
        boolean signVerfied = false;
        try {
            signVerfied = AlipaySignature.rsaCheck(content, sing, this.alipayConfig.getAlipayPublicKey(), this.alipayConfig.getCharset(), "RSA2");
        } catch (AlipayApiException e) {
            e.printStackTrace();
            LOGGER.error("校验签名异常" + paramMap.toString());
            return null;
        }
        if (signVerfied) {

            AliPayPost aliPayPost = new AliPayPost();
            aliPayPost.setTradeNo(paramMap.get("trade_no"));
            aliPayPost.setAlipayTotalAmount(paramMap.get("total_amount"));
            aliPayPost.setOutTradeNo(paramMap.get("out_trade_no"));
            try {
                aliPayPost.setPayDate(DateUtil.strToFullDate(paramMap.get("gmt_payment")));
            } catch (ParseException e) {
                e.printStackTrace();
                LOGGER.error("转日期异常", e);
            }

            return aliPayPost;
        }
        return null;
    }


    private static String buildKeyValue(String key, String value, boolean isEncode) {
        StringBuilder sb = new StringBuilder();
        sb.append(key);
        sb.append("=");
        if (isEncode) {
            try {
                sb.append(URLEncoder.encode(value, "UTF-8"));
            } catch (UnsupportedEncodingException e) {
                sb.append(value);
            }
        } else {
            sb.append(value);
        }
        return sb.toString();
    }
}
